<template>
  <div>
    <h2>随机点名</h2>
    <div class="box">
      <span>名字是：</span>
      <div class="qs">{{userName}}</div>
    </div>
    <div class="btns">
      <button class="start" @click="startFn">开始</button>
      <button class="end" @click="endFn">结束</button>
    </div>
  </div>
</template>

<script>
export default {
   data() {
    return {
      userName:'这里显示姓名',
      nameArr: ['孙悟空','唐僧','猪八戒','沙僧','杨戬'],
      timer:null,// 保存计时器
      isHave:false // 保存计时器 状态
    }
   },
   methods:{
    getRandom(min,max) {
      return Math.floor(Math.random() * (max-min +1) + min)
    },
    startFn() {
      if(this.isHave === true) return
      this.isHave = true // 有一个计时器正在运行
      this.timer = setInterval(() => {
        // console.log(1)
        let index = this.getRandom(0,this.nameArr.length -1)
        this.userName = this.nameArr[index]
      }, 100);  
    },
    endFn() {
      clearInterval(this.timer)
      this.isHave = false
    }

   }
};
</script>

<style>
* {
  margin: 0;
  padding: 0;
}

h2 {
  text-align: center;
}

.box {
  width: 600px;
  margin: 50px auto;
  display: flex;
  font-size: 25px;
  line-height: 40px;
}

.qs {
  width: 450px;
  height: 40px;
  color: red;
}

.btns {
  text-align: center;
}

.btns button {
  width: 120px;
  height: 35px;
  margin: 0 50px;
}
</style>